//
//  ZGLNewsViewController.m
//  ZeegingLottery
//
//  Created by 李曌 on 2018/10/18.
//  Copyright © 2018 蒂埃里. All rights reserved.
//

#import "ZGLNewsViewController.h"
#import "ZGLRecordDetailController.h"
#import "ZGLNewsHeaderView.h"
#import "ZGLNewsSectionHeader.h"
#import "ZGLNewsCell.h"
#import "ZGLNewsModel.h"
#import "LYDFMDB.h"


static NSString *ZGLNewsSectionHeaderID = @"ZGLNewsSectionHeaderID";
static NSString *dataBaseName = @"zglNews.sqlite";
static NSString *tableName = @"News";
@interface ZGLNewsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *NewsListView;
@property (nonatomic, strong) ZGLNewsHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *bannerImages;
@property (nonatomic, strong) NSMutableArray *DataArray;

@property (nonatomic, strong) LYDFMDB *db;

@end

@implementation ZGLNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = ViewBackgroundColor;
    
    [self.view addSubview:self.NewsListView];
    [_NewsListView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view).offset(5);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
//        make.bottom.equalTo(self.view).offset(-STATUEHEIGHT);
        
    }];
    self.NewsListView.tableHeaderView = self.headerView;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //查看数据库
        if (![ZGLNewsModel isExistInTable]) {
            
            //菊花
            [EasyLoadingView showLoadingText:@"正在努力加载中..." config:^EasyLoadingConfig *{
                return [EasyLoadingConfig shared].setLoadingType(LoadingShowTypeIndicator);
            }];
            
            //建表
            [ZGLNewsModel createTable];
            
            //请求数据
            [self getNewsListData];
            
        }else{
            
            [EasyLoadingView hidenLoading];
            [self.DataArray removeAllObjects];
            
            //从数据库导出数据
            NSArray *array = [ZGLNewsModel findAll];
            _DataArray = array.mutableCopy;
            DLog(@"SQL-%@",_DataArray);
            [self.NewsListView reloadData];

        }
    });
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _DataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZGLNewsCell *cell = [ZGLNewsCell NewsCellWithTableView:tableView];
    cell.model = self.DataArray[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZGLNewsModel *model = self.DataArray[indexPath.row];
    NSString *urlStr = [NSString stringWithFormat:@"http://betdata.zeeging.com/index.php/index/getSinaSportsNewsContent?url=%@",model.url];
    WKWebViewController *webView = [[WKWebViewController alloc]init];
    webView.isNavHidden = YES;
    [webView loadWebURLSring:urlStr];
    
    
    [self.navigationController pushViewController:webView animated:YES];
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ZGLNewsSectionHeader *sectionHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ZGLNewsSectionHeaderID];
    
    UIView *bgColorView = [[UIView alloc]initWithFrame:sectionHeader.bounds];
    bgColorView.backgroundColor = [UIColor whiteColor];
    sectionHeader.backgroundView = bgColorView;
    
    return sectionHeader;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

#pragma mark - method

- (void)getNewsListData
{
    [sZGLHTTPRequestManager getNewsListDataSuccess:^(id responsedata) {
        
        NSDictionary *repoDict = responsedata;
        NSInteger count = repoDict.count ;
        [_DataArray removeAllObjects];
        
        //清空表
        [ZGLNewsModel clearTable];
        
        for (int i = 0; i<count; i++) {
            NSString *key = [NSString stringWithFormat:@"%d",i];
            NSDictionary *dict = [repoDict objectForKey:key];
            ZGLNewsModel *model = [ZGLNewsModel mj_objectWithKeyValues:dict];
            [self.DataArray addObject:model];
            
            //存储数据
            [model save];
        }
        
        WS(weakself)
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [EasyLoadingView hidenLoading];
            
            [weakSelf.NewsListView reloadData];
            [weakSelf.NewsListView.mj_header endRefreshing];
            
        });
        
        DLog(@"DataArraycount-%ld",_DataArray.count);
        
    } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
        
        
    }];
    
}

#pragma mark - getter&setter

- (void)setImageArr:(NSArray<ZGLNewsBannerImageModel *> *)imageArr
{
    _imageArr = imageArr;
    
    for (ZGLNewsBannerImageModel *model in imageArr) {
        [self.bannerImages addObject:model.img];
    }
    DLog(@"_bannerImages-%@",_bannerImages);
}

- (void)setMatchArr:(NSArray *)matchArr
{
    _matchArr = matchArr;
    
}

- (NSMutableArray *)bannerImages
{
    if (!_bannerImages) {
        _bannerImages = [NSMutableArray array];
    }
    return _bannerImages;
}

- (UITableView *)NewsListView
{
    if (!_NewsListView) {
        _NewsListView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _NewsListView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _NewsListView.delegate = self;
        _NewsListView.dataSource = self;
        [_NewsListView registerNib:[UINib nibWithNibName:@"ZGLNewsSectionHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:ZGLNewsSectionHeaderID];
        //下拉刷新
        WS(weakself)
        MJRefreshNormalHeader *refreshheader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [weakSelf getNewsListData];
            
        }];
        refreshheader.lastUpdatedTimeLabel.hidden = YES;
        _NewsListView.mj_header = refreshheader;
        
    }
    return _NewsListView;
}

- (ZGLNewsHeaderView *)headerView
{
    if (!_headerView) {
        CGFloat H = IS_IPHONE_4and5?200:250;
        _headerView = [[ZGLNewsHeaderView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, H)];
        
        //轮播图赋值
//        _headerView.imageArray = [NSArray arrayWithObjects:@"G1",@"G2",@"G3",@"G4",@"G5", nil];
        _headerView.imageArray = self.bannerImages.copy;
        _headerView.matchArray = self.matchArr;
    }
    return _headerView;
}

- (NSMutableArray *)DataArray
{
    if (!_DataArray) {
        _DataArray = [[NSMutableArray alloc]init];
    }
    return _DataArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
